package com.youaishujuhui.devops.web.controller.game;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.youaishujuhui.devops.web.domain.game.Game;
import com.youaishujuhui.devops.web.service.game.GameService;
import com.youaishujuhui.devops.web.vo.Result;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RuntimeUtil;

@Controller
@RequestMapping("/game/combine")
public class GameCombineController {
	
	@Autowired
	private GameService gameService;
	
    @RequestMapping("/page")
    public ModelAndView page(){
        return new ModelAndView("game/combine");
    }
    
    @RequestMapping("/combine")
    @ResponseBody
    public Result<String> combine(Integer gameId, String combineTxt, String combineListTxt, String combine_motherTxt, String versionTxt){
        Result<String> result = new Result<>();

        Game game = gameService.fetch(gameId);
        
        String basePath = "/data/" + game.getNameEn() + "_combine";
        String configPath = basePath + "/config";
        String logPath = "/tmp/hf.log" + System.currentTimeMillis();
        
        if (!System.getProperty("os.name").toLowerCase().startsWith("win")){
			// 本机执行git pull保持更新脚本最新，只在linux上执行
			String cmd = "cd " + basePath + "; git pull > " + logPath + " 2>&1";
			RuntimeUtil.execForStr("sh", "-c", cmd);
		} else {
			configPath = "C:/Users/Administrator/Desktop/hfconfig";
		}
        
		// 将配置文件写到config文件夹中
        FileUtil.writeUtf8String(combineTxt, configPath + "/combine.txt");
        FileUtil.writeUtf8String(combineListTxt, configPath + "/combineList.txt");
        FileUtil.writeUtf8String(combine_motherTxt, configPath + "/combine_mother.txt");
        FileUtil.writeUtf8String(versionTxt, configPath + "/version.txt");
        
        // 执行脚本
        if (!System.getProperty("os.name").toLowerCase().startsWith("win")){
			// 本机执行git pull保持更新脚本最新，只在linux上执行
			String cmd = "cd " + basePath + "; chmod +x ./combineTools.sh; nohup " + "./combineTools.sh >> " + logPath + " 2>&1 &";
			RuntimeUtil.execForStr("sh", "-c", cmd);
		}
        
        result.setData(logPath);
        result.setCode(Result.SUCCESS);
        result.setMsg("成功！");
        return result;
    }
}
